﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FunDraw.LayerInfos;

namespace FunDraw.usercontrols
{
    public partial class LayerList : UserControl
    {
        private LayerInfoList layerinfoList=new LayerInfoList();
        //绘制图层列表
        private List<MyDrawLayer> list_drawlayer=new List<MyDrawLayer>();

        private Panel lyparent=null;

        /// <summary>
        /// 选中值发生变化的事件
        /// </summary>
        public event EventHandler valuechange;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Category("Action")]
        public event EventHandler OnValueChange
        {
            add
            {
                valuechange += value;
            }
            remove
            {
                valuechange -= value;
            }
        }

        protected virtual void Onvaluechange(object sender, EventArgs e)
        {
            valuechange.Invoke(sender, e);
        }


        public LayerList()
        {
            InitializeComponent();
            layerinfoList = new LayerInfoList();
        }
        /// <summary>
        /// 设置图层父控件
        /// </summary>
        /// <param name="layerParent"></param>
        public void setLayerParent(Panel layerParent)
        {
            lyparent = layerParent;

            MyDrawLayer mdl = list_drawlayer[list_drawlayer.Count - 1];
            layerParent.Controls.Add(mdl);
            mdl.Dock = DockStyle.Fill;
            mdl.BringToFront();
        }

        /// <summary>
        /// 添加新的绘制图层
        /// </summary>
        /// <param name="lyt">图层类别</param>
        /// <param name="lyname">图层名称</param>
        public void appendNewDrawLayer(LAYERTYPE lyt,Panel layerParent,LayerSize lys, MouseEventHandler ME, string lyname="")
        {

         
            try
            {

                LayerInfo newLayer = null;
                if (lyname == string.Empty)
                {
                    newLayer= layerinfoList.AppendNewLayerInfo(lyt);
                }
                else
                {
                    newLayer= layerinfoList.AppendNewLayerInfo(lyt, lyname);
                }
                ListViewItem lvi = lv_layer.Items.Add("");
                lvi.ImageIndex = 0;
                lvi.SubItems.Add(newLayer.FriendlyType);
                lvi.SubItems.Add(newLayer.LayerName);
                lvi.SubItems.Add(newLayer.id);
               
          
                //根据不同的图层类型向方程列表中添加方程接口
                if (lyt==LAYERTYPE.LINE)
                {
                    LineEquation line = new LineEquation();
                    line.layersize = lys;

                    MyDrawLayer newdrawlayer = new MyDrawLayer();
                    newdrawlayer.MouseMove += ME;
                    newdrawlayer.Opacity = 1;
                    newdrawlayer.equation = (IntEquation)line;
                    list_drawlayer.Add(newdrawlayer);
                    setLayerParent(layerParent);

                }
                else if (lyt == LAYERTYPE.POINT)
                {

                }
                else if(lyt==LAYERTYPE.SIN)
                {

                }
                else if(lyt==LAYERTYPE.COS)
                {

                }
                else if(lyt==LAYERTYPE.EQUATION)
                {

                }
            }catch(Exception ex)
            {
                
            }
        }

        /// <summary>
        /// 删除选中的绘制图层
        /// </summary>
        public void deleteSelected()
        {
            try
            {
                ListView.CheckedIndexCollection cic = lv_layer.CheckedIndices;
                while(cic.Count>0)
                {
                    int idx = cic[0];
                    string lyid = lv_layer.Items[idx].SubItems[3].Text;
                    layerinfoList.RemoveLayerByID(lyid);
                    MyDrawLayer mdl = list_drawlayer[idx];
                    lyparent.Controls.Remove(mdl);
                    list_drawlayer.Remove(mdl);
                    ListViewItem selitem = lv_layer.Items[cic[0]];
                    lv_layer.Items.Remove(selitem);
                    cic = lv_layer.CheckedIndices;
                }
            }
            catch
            {

            }
        }


        /// <summary>
        /// 判定是否存在选中的item
        /// </summary>
        /// <returns></returns>
        public bool checkHaveCheck()
        {
            ListView.CheckedIndexCollection cic = lv_layer.CheckedIndices;
            if (cic.Count > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 重命名选中的图层
        /// </summary>
        /// <param name="newLayName">新图层名称</param>
        public void RnameLayer(string newLayName)
        {
            ListView.CheckedIndexCollection cic = lv_layer.CheckedIndices;
            if(cic.Count>0)
            {
                try
                {
                    int idx = cic[0];
                    ListViewItem item = lv_layer.Items[idx];
                    string lyid = item.SubItems[3].Text;
                    item.SubItems[2].Text = newLayName;
                    //更改层信息列表中代表该图层的名称
                    LayerInfo lyinfo = layerinfoList.GetLayerInfoByID(lyid);
                    lyinfo.LayerName = newLayName;
                }
                catch(Exception ex)
                {
                    Console.WriteLine(string.Format("重命名图层出现异常:{0}", ex.Message.ToString()));
                }
                
            }
        }

        

        /// <summary>
        /// 上移选中图层  
        /// </summary>
        public void moveUpSelected()
        {
            ListView.SelectedIndexCollection sic = lv_layer.SelectedIndices;
            //当sic为null或者只有一个图层，或者选中图层为第一个图层时
            if(sic.Equals(null)||sic.Count<=0||sic[0]<=0)
            {
                return;
            }
            int idx = sic[0];
            int p_idx = idx - 1;
            string layerid = lv_layer.Items[idx].SubItems[3].Text;
            //上移列表中的item
            ListViewItem lvi =(ListViewItem) lv_layer.Items[p_idx].Clone();
            ListViewItem lvc = (ListViewItem)lv_layer.Items[idx].Clone();
            lv_layer.Items.RemoveAt(p_idx);
            lv_layer.Items.Insert(p_idx, lvc);
            lv_layer.Items.RemoveAt(idx);
            lv_layer.Items.Insert(idx,lvi);
            //在图层信息列表中上移图层信息
            layerinfoList.MoveUp(layerid);
            //在图层列表中前移图层
            MyDrawLayer mdl = list_drawlayer[p_idx];
            list_drawlayer[p_idx] = list_drawlayer[idx];
            list_drawlayer[idx] = mdl;
            //在父背景层中迁移图层
            for(int i=idx;i>=0;i--)
            {
                if(i!=p_idx)
                {
                    MyDrawLayer md = (lyparent.Controls[idx] as MyDrawLayer);
                    md.BringToFront();
                }
            }
            
        }

        /// <summary>
        /// 下移选中图层
        /// </summary>
        public void moveDownSelected()
        {
            ListView.SelectedIndexCollection sic = lv_layer.SelectedIndices;
            //当sic为null或者只有一个图层，或者选中图层为第最后个图层时
            if (sic.Equals(null) || sic.Count <= 0 || sic[0] >= lv_layer.Items.Count-1)
            {
                return;
            }
            int idx = sic[0];
            int n_idx = idx + 1;
            string layerid = lv_layer.Items[idx].SubItems[3].Text;

            //下移列表中的item
            ListViewItem lvi = (ListViewItem)lv_layer.Items[n_idx].Clone();
            ListViewItem lvc = (ListViewItem)lv_layer.Items[idx].Clone();
            lv_layer.Items.RemoveAt(idx);
            lv_layer.Items.Insert(idx, lvi);
            lv_layer.Items.RemoveAt(n_idx);
            lv_layer.Items.Insert(n_idx, lvc);
            //在图层信息列表中上移图层信息
            layerinfoList.MoveDown(layerid);
            
            //在图层列表中前移图层
            MyDrawLayer mdl = list_drawlayer[n_idx];
            list_drawlayer[n_idx] = list_drawlayer[idx];
            list_drawlayer[idx] = mdl;
            //在背景图层中向下移动选中图层
            for(int i=idx;i<=list_drawlayer.Count-1;i++)
            {
                if(i!=n_idx)
                {
                    MyDrawLayer MD = (list_drawlayer[idx] as MyDrawLayer);
                    MD.SendToBack();
                }
            }
        }


        /// <summary>
        /// 变更图层的可视化状态
        /// </summary>
        /// <param name="visable">图层的可视化状态</param>
        public void changeVisableLayer(bool visable)
        {
            try
            {
                ListView.CheckedIndexCollection sic = lv_layer.CheckedIndices;
                //当sic为null或没有选中时
                if (sic.Equals(null) || sic.Count <= 0)
                {
                    return;
                }
                for (int i = 0; i <= sic.Count - 1; i++)
                {
                    int idx = sic[i];
                    list_drawlayer[idx].Visible = visable;
                    //图层信息列表中的图层信息对象的显示状态变更成visable
                    string id = lv_layer.Items[idx].SubItems[3].Text;
                    LayerInfo lyi = layerinfoList.GetLayerInfoByID(id);
                    lyi.Visable = visable;
                    //变更列表图标
                    if (visable)
                        lv_layer.Items[idx].ImageIndex = 0;
                    else
                        lv_layer.Items[idx].ImageIndex = 1;
                }
            }
            catch
            {

            }

        }

        /// <summary>
        /// 重新绘制所有图层
        /// </summary>
        public void RefreshDrawLayer(LayerSize lys)
        {
            foreach(MyDrawLayer mdl in list_drawlayer)
            {
                (mdl.equation as BaseEquation).layersize = lys;
                if (mdl.Visible)
                {
                    mdl.Invalidate();
                }
            }
        }

        /// <summary>
        /// 获取列表项个数
        /// </summary>
        /// <returns></returns>
        public int GetItemCount()
        {
            return lv_layer.Items.Count;
        }

        /// <summary>
        /// 通过ID获取方程对象
        /// </summary>
        /// <param name="ID">id</param>
        /// <returns>方程对象</returns>
        public BaseEquation GetEquationByID(string ID)
        {
            int idx = layerinfoList.GetLayerIndexByID(ID);
            if(idx>=0)
            {
                return list_drawlayer[idx].equation as BaseEquation;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 通过ID获取绘制图层
        /// </summary>
        /// <param name="ID">ID</param>
        /// <returns>绘制图层</returns>
        public MyDrawLayer GetDrawLayerByID(string ID)
        {
            int idx = layerinfoList.GetLayerIndexByID(ID);
            if (idx >= 0)
            {
                return list_drawlayer[idx];
            }
            else
            {
                return null;
            }
        }


        
        /// <summary>
        /// 图层列表绘制表头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lv_layer_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            e.Graphics.FillRectangle(Brushes.Gainsboro, e.Bounds);
            TextRenderer.DrawText(e.Graphics, e.Header.Text, e.Font, e.Bounds, Color.Black, TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter);
        }



        public void testaddview()
        {
            ListViewItem lvitem = lv_layer.Items.Add("test");
        }

        private void lv_layer_SelectedIndexChanged(object sender, EventArgs e)
        {
            Onvaluechange(sender, e);
        }
    }
}
